<template>
  <div class="img-manager">
    <el-dialog title="图片选择器" :visible.sync="isShowDialog" width="1000px">
      <div class="content">
        <div class="left">
          <div v-for="item in imgCate" :key="item.id" class="list-item" :class="{ active: item.id == currentCate }" @click="changeImgCate(item.id)">
            {{ item.name }}
          </div>
        </div>
        <div class="right">
          <div class="top">
            <span>图片（image）:2M，支持bmp/png/jpeg/jpg/gif格式</span>
            <!-- <el-button type="primary" icon="el-icon-plus" @click="uploadImg">上传图片</el-button> -->
            <!-- <el-upload :action="domain + '?pid=' + currentCate" :data="QiniuData" auto-upload :on-success="uploadImg" :on-error="uploadFail" :headers="headers" :show-file-list="false">
              <el-button size="small" icon="el-icon-plus" type="primary">上传图片</el-button>
            </el-upload> -->
            <el-button size="small" icon="el-icon-plus" type="primary" @click="checkedFile">上传图片</el-button>
            <input type="file" ref="file" @change="uploadFileChange" style="display: none" />
          </div>
          <div class="img-list" v-if="imgList.length != 0">
            <div class="img-item" v-for="(item, index) in imgList" :key="index">
              <div class="img-box">
                <div class="btns">
                  <el-button type="warning" icon="el-icon-zoom-in" circle @click.stop="previewImg(item.img)"></el-button>
                  <el-button type="danger" icon="el-icon-close" circle @click.stop="removeImg(item.id)"></el-button>
                </div>
                <el-image :src="imgUrl + item.img" fit="cover" @click="checkImg(item)"></el-image>
                <div class="img-name">{{ item.name }}</div>
              </div>
              <div class="mask" v-if="item.checked">
                <i class="el-icon-check"></i>
              </div>
            </div>
          </div>
          <div v-else>
            <no-data msg="当前分类暂无图片" type="2"></no-data>
          </div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <div class="page">
          <pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :total="total" :page-sizes="[10]"></pagination>
        </div>
        <div class="btns">
          <el-button @click="isShowDialog = false">取 消</el-button>
          <el-button type="primary" @click="submitImg">确 定</el-button>
        </div>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getImgList, removeImg, getQiniuToken } from '@/api/common'
import { mapGetters } from 'vuex'
import { timeFormat } from '@/utils'

import * as qiniu from 'qiniu-js'

export default {
  name: 'ImgManager',
  props: {},
  data() {
    return {
      queryInfo: {
        page: 1,
        page_size: 10,
      },
      total: 0,
      isShowDialog: false,
      imgCate: [
        {
          id: 0,
          name: '全部',
        },
        {
          id: 1,
          name: '站点',
        },
        {
          id: 2,
          name: '工具',
        },
      ],
      currentCate: 0,
      imgList: [],
      headers: {
        token: localStorage.getItem('token'),
      },
      domain: '',
      index: '',
      QiniuData: {
        token: '',
        key: '',
      },
    }
  },
  created() {},
  methods: {
    checkedFile() {
      this.$refs.file.click()
    },
    getDate() {
      let date = timeFormat(Date.parse(new Date()) / 1000, 'yy/mm/dd')
      return date
    },
    async uploadFileChange(e) {
      const res = await getQiniuToken()
      if (res.code != 1) return this.$message.error(res.msg)
      const uptoken = res.data.token
      const upFile = e.target.files[0] //Blob 对象，上传的文件
      const key = 'images/' + this.getDate() + '/' + upFile.name // 上传后文件资源名以设置的 key 为主，如果 key 为 null 或者 undefined，则文件资源名会以 hash 值作为资源名。
      const putExtra = {
        fname: '', //文件原文件名
        customVars: {
          'x:pid': this.currentCate,
          'x:name': upFile.name,
          'x:size': (upFile.size / 1000).toFixed(1) + 'KB',
          'x:type': upFile.type,
        }, //用来放置自定义变量   bmp/png/jpeg/jpg/gif
        mimeType: ['image/png', 'image/jpeg', 'image/gif', 'image/jpg', 'image/bmp'], //用来限制上传文件类型，为 null 时表示不对文件类型限制；限制类型放到数组里： ["image/png", "image/jpeg", "image/gif"]
      }
      const config = {
        useCdnDomain: false, //表示是否使用 cdn 加速域名，为布尔值，true 表示使用，默认为 false。
        region: qiniu.region.z2, // 根据具体提示修改上传地区,当为 null 或 undefined 时，自动分析上传域名区域
      }
      const observable = qiniu.upload(upFile, key, uptoken, putExtra, config)
      observable.subscribe({
        next: result => {
          // 主要用来展示进度
        },
        error: errResult => {
          // 失败报错信息
          let msg = ''
          if (errResult.code == 614) {
            msg = '图片已存在'
          }
          if (errResult.code == 579) {
            msg = '服务端回调错误'
          }
          this.$message.error('上传失败，' + msg)
        },
        complete: res => {
          // 接收成功后返回的信息
          // console.log(res)
          if (res.code != 1) return this.$message.error(res.msg)
          this.$message.success('图片上传成功')
          this.getImgList()
        },
      })
      // 重置图片input
      e.target.value = ''
    },
    async getQiniuToken() {
      const res = await getQiniuToken()
      if (res.code != 1) return this.$message.error(res.msg)
      this.QiniuData.token = res.data.token
      this.domain = res.data.domain
    },
    showDialog(index) {
      this.isShowDialog = true
      this.index = index
      this.getImgList()
    },
    changeImgCate(id) {
      this.currentCate = id
      this.getImgList()
    },
    async getImgList() {
      const res = await getImgList({ pid: this.currentCate, ...this.queryInfo })
      if (res.code != 1) return this.$message.error(res.msg)
      res.data.data.forEach(x => {
        this.$set(x, 'checked', false)
      })
      this.imgList = res.data.data
      this.total = res.data.total
    },
    checkImg(item) {
      this.imgList.forEach(x => {
        x.checked = false
      })
      item.checked = true
    },
    submitImg() {
      let img = this.imgList.filter(x => x.checked)
      if (img.length != 0) {
        this.$emit('change', img[0].img, this.index)
      }
      this.isShowDialog = false
      // console.log(img)
    },
    previewImg(url) {
      window.open(this.imgUrl + url, '_blank')
    },
    uploadImg(res) {
      // console.log(res)
      if (res.code != 1) return this.$message.error('上传失败，' + res.msg)
      this.$message.success('图片上传成功')
      this.getImgList()
    },
    uploadFail() {
      this.$message.error('图片上传失败')
    },
    removeImg(id) {
      this.$confirm('此操作将永久删除该图片, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          const res = await removeImg(id)
          if (res.code != 1) return this.$message.error(res.msg)
          this.$message.success('删除成功')
          this.getImgList()
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除',
          })
        })
    },
    handleSizeChange(newSize) {
      this.queryInfo.page_size = newSize
      this.getImgList()
    },
    handleCurrentChange(newPage) {
      this.queryInfo.page = newPage
      this.getImgList()
    },
  },
  computed: {
    ...mapGetters({
      imgUrl: 'settings/imgUrl',
    }),
  },
}
</script>

<style lang="scss" scoped>
::v-deep .el-dialog {
  border-radius: 6px;
}
::v-deep .el-dialog__body {
  padding: 4px 0;
}

.img-manager {
  ::v-deep .el-pagination .el-select .el-input {
    width: 100px !important;
    .el-input__inner {
      height: 28px !important;
      width: 100% !important;
    }
  }
  ::v-deep .el-pagination__editor.el-input {
    width: 50px !important;
    .el-input__inner {
      height: 28px !important;
      width: 100% !important;
    }
  }
  .content {
    display: flex;
    justify-content: space-between;
    height: 520px;
    .left {
      padding: 20px;
      width: 160px;
      max-width: 180px;
      border-right: 1px solid #f1f1f1;
      box-sizing: border-box;
      .list-item {
        height: 36px;
        text-align: center;
        line-height: 36px;
        margin-bottom: 16px;
        border-radius: 6px;
        cursor: pointer;
      }
      .active {
        background: #c3e1fe;
        color: #409eff;
      }
    }
    .right {
      // flex: 1;
      width: 840px;
      .top {
        display: flex;
        align-items: center;
        justify-content: flex-end;
        height: 60px;
        padding-right: 50px;
        // margin-left: 20px;
        span {
          margin-right: 20px;
          color: #999;
          font-size: 13px;
        }
      }
      .img-list {
        display: flex;
        flex-wrap: wrap;
        padding: 20px;
        .img-item {
          position: relative;
          width: 148px;
          margin: 0 14px 28px 0;
          .img-box {
            position: relative;
            .el-image {
              width: 148px;
              height: 148px;
              border-radius: 6px;
              cursor: pointer;
            }
            .btns {
              position: absolute;
              right: 0;
              top: 0;
              transform: translate(9px, -50%);
              // transform: translateY(-50%);
              opacity: 0;
              z-index: 1;
              font-size: 18px;
              color: #999;
              transition: 0.3s;
              .el-button {
                padding: 3px;
                margin-left: 6px;
              }
            }
            .img-name {
              width: 100%;
              text-align: center;
              padding-right: 10px;
              white-space: nowrap;
              overflow: hidden;
              text-overflow: ellipsis;
              color: #666;
              font-size: 13px;
            }
          }
          &:hover {
            .btns {
              opacity: 1;
            }
          }
          .mask {
            position: absolute;
            top: 0;
            left: 0;
            display: flex;
            align-items: center;
            justify-content: center;
            width: 148px;
            height: 148px;
            border-radius: 6px;
            z-index: 1;
            background-color: rgba($color: #000, $alpha: 0.1);
            cursor: pointer;
            i {
              font-size: 32px;
              color: #fff;
              font-weight: bold;
              &:hover {
                opacity: 1;
              }
            }
          }
        }
        .img-item:nth-child(5n) {
          margin-right: 0;
        }
      }
    }
  }
  .dialog-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
}
::v-deep .el-pagination.is-background {
  margin: 0;
}
::v-deep .el-upload-list {
  display: none;
}
</style>
